package org.summer.gateway.security;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.summer.common.http.Result;
import org.summer.common.http.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.summer.gateway.handler.ServerResponseHandler;
import reactor.core.publisher.Mono;

/**
 * 用户身份认证失败处理
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class AuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    private final ServerResponseHandler responseHandler;
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        HttpStatusCode statusCode = exchange.getResponse().getStatusCode();
        assert statusCode != null;
        if ("false".equals(exchange.getAttributes().get("AuthorizationDecision"))){
            return Mono.empty();
        }
        if (HttpStatus.FAILED_DEPENDENCY.isSameCodeAs(statusCode)){
            log.warn("用户登录令牌过期,请重新登录");
            return responseHandler.handlerResponse(exchange, Result.fail(ResultCode.TOKEN_EXPIRE));
        }
        log.info("用户为身份未经过认证:{}",exchange.getAttributes());
        return responseHandler.handlerResponse(exchange, Result.fail(ResultCode.UNAUTHORIZED));
    }
}
